<template>
  <div id="grecaptcha"></div>
</template>

<script lang="ts" setup>
import { onMounted, ref, computed } from 'vue';
import { googleRecaptchaVerify } from '@/server/api/auth.js';
import Cookies from 'js-cookie';

const sitekey = '6Lc6qB0pAAAAAGxHjPGwP12xnvJu56CX9Q2kYvrk';
const emit = defineEmits(['changeRobotCertification']);
const grecaptchaToken = ref('');
const isRobotCertification = computed(() => grecaptchaToken.value === '');

/**
 * 动态加载grecaptcha脚本
 */
const loadRecaptchaScript = () => {
  return new Promise((resolve, reject) => {
    const scriptId = 'recaptcha-script';
    if (document.getElementById(scriptId)) {
      resolve();
      return;
    }
    const script = document.createElement('script');
    script.id = scriptId;
    script.src = 'https://www.google.com/recaptcha/api.js?render=explicit';
    script.async = true;
    script.defer = true;
    script.onload = resolve;
    script.onerror = reject;
    document.head.appendChild(script);
  });
};

const getLanguage = (lang) => {
  switch (lang) {
    case 'zhCN':
      return 'zh';
    case 'en':
      return 'en';
  }
};

/**
 * 加载grecaptcha
 */
const renderRecaptcha = () => {
  const lang = getLanguage(Cookies.get('language') || 'en');
  if (window.grecaptcha) {
    window.grecaptcha.ready(() => {
      window.grecaptcha.render('grecaptcha', {
        sitekey: sitekey,
        hl: lang, // 国际化
        callback: submit,
      });
    });
  } else {
    console.error('grecaptcha is not available');
  }
};

/**
 * 触发submit事件
 * @param {*} token
 */
const submit = (token) => {
  console.log('token', token);
  grecaptchaToken.value = token;
  verifyGrecaptchaKey(token);
};

/**
 * 验证grecaptchaKey
 */
const verifyGrecaptchaKey = (token) => {
  googleRecaptchaVerify({ recaptchaToken: token })
    .then((res) => {
      console.log('res', res);
      if (res.data.success === true) {
        emit('changeRobotCertification', true);
      }
    })
    .catch((error) => {
      console.error('Error verifying reCAPTCHA', error);
    });
};

onMounted(() => {
  if (isRobotCertification.value) {
    loadRecaptchaScript()
      .then(() => {
        renderRecaptcha();
      })
      .catch((error) => {
        console.error('Failed to load reCAPTCHA script', error);
      });
  }
});
</script>
